package com.runfast.paotui.config;

import com.runfast.paotui.task.async.MessagePushTask;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.lang.reflect.Method;
import java.util.concurrent.Executor;

/**
 * @author: lijin
 * @date: 2018年04月26日
 */
@Slf4j
public class Async implements AsyncConfigurer {

     @Override
    @Bean
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(20);
        return executor;
    }

    @Override
    @Bean
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new AsyncUncaughtExceptionHandler() {
            @Override
            public void handleUncaughtException(Throwable ex, Method method, Object... params) {
                Class<?> declaringClass = method.getDeclaringClass();
                if (MessagePushTask.class.isAssignableFrom(declaringClass)) {

                    log.error(String.format("异步消息推送错误，方法： " + "%s 参数：", method, ArrayUtils.toString(params)), ex);
                }
            }
        };
    }
}
